<?php
/**
 * Created by PhpStorm.
 * User: HuangLuSen
 * Date: 2017/5/3
 * Time: 14:49
 */

namespace app\index\controller;

use app\api\controller\Client;
use app\api\controller\User;
use app\common\controller\Base;
use think\Cache;
use think\Db;
use think\Session;

/**
 * Class Login
 * 主要处理登录逻辑
 * @package app\admin\controller
 * @internal
 */
class Login extends Base
{
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     *绑定页面
     * @icon wocap
     */
    public function index()
    {
        $userweixininfo = session('user_weixin');
        $data = Db::name('users')->where('openid', $userweixininfo['id'])->fetchSql(false)->find();
        if (!empty($data)) {
            return $this->fetch('success');
        } else {
            $this->assign('info', $userweixininfo);
            return $this->fetch();
        }
    }

    /**
     * 保存绑定页面
     * @return mixed
     * @author: Huang
     */
    public function validate()
    {
        $data = $this->request->post();
        if (empty($data['phone'])) $this->error('号码不能为空！');
        $clent = new Client();
        $userinfo = collect($clent->getAllUserInfo(true));
        $userdata = $userinfo->where('phone',$data['phone'])->first();
        $user = Db::name('users')->where(['id' => $userdata['id'], 'weixinstatus' => 2])->find();
        if ($user['status'] == 0) $this->error('号码已经被禁用了，请联系管理员！');
        if ($user) {
            $userweixininfo = session('user_weixin');
            $re = Db::name('users')->where(['id' => $user['id']])->update(['openid' => $data['openid'],'avatar'=>$userweixininfo['avatar'], 'weixinstatus' => 1,'token'=>config('index.we_options')['we_id'],'weixininfo'=>json_encode($userweixininfo)]);
            if ($re) {
                \app\common\logic\Login::auto_login([
                    'username'=>$userdata['username'],
                    'id'=>$userdata['id']
                ]);
                Cache::clear('alluser');
                return $this->success('绑定成功',session('url'));
            } else {
                $this->error('绑定失败，请联系管理员！');
            }
        } else {
            $this->error('绑定失败，系统没有找到该号码，或者该号码已经被绑定了，或是被禁用了');
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        session('admin_user', null);
        $this->redirect('index/Login/login');
    }
}